package com.oneguy.control.timer;

import com.oneguy.Cache;
import com.oneguy.Log;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by ZuoShu on 16/12/7.
 */
public class TaskManager implements Runnable {
    public static final String TAG = "TaskManager";
    private static final int INTERNAL = 30000;

    private boolean stop;

    private List<TimerTask> taskList = null;

    private Object mutext = new Object();

    public TaskManager() {
        stop = false;
        taskList = new ArrayList<TimerTask>();
    }

    public void start() {
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {
        while (!stop) {
            TimerTask task = popExecutableTask();
            if (task != null) {
                Log.i(TAG, "Executing timer task:" + task.toString());
                Cache.getInstance().setRoom(task.getRoomId(), task.getTableId(), task.getFactor());
            }
            try {
                Thread.sleep(INTERNAL);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private TimerTask popExecutableTask() {
        TimerTask setToTask = null;
        synchronized (mutext) {
            if (taskList == null || taskList.size() == 0) {
                return setToTask;
            }
            Collections.sort(taskList);
            List<TimerTask> remove = new ArrayList<TimerTask>();
            for (int i = 0; i < taskList.size(); i++) {
                if (System.currentTimeMillis() >= taskList.get(i).getTime()) {
                    setToTask = taskList.get(i);
                    remove.add(setToTask);
                } else {
                    break;
                }
            }
            taskList.removeAll(remove);
        }
        return setToTask;
    }

    public void addTask(TimerTask task) {
        synchronized (mutext) {
            taskList.add(task);
        }
    }

    public void clearTask() {
        synchronized (mutext) {
            taskList.clear();
        }
    }

    public boolean isStop() {
        return stop;
    }

    public List<TimerTask> getTaskList() {
        return taskList;
    }
}
